import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import Home from '../views/Home.vue'
import Article from '../views/Article.vue'
import Login from '../views/Login.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      title: '登录'
    }
  },
  {
    path: '/register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/article/:id',
    name: 'article',
    component: Article
  },
  {
    path: '/user/:id',
    component: () => import('../views/UserProfile.vue')
  },
  {
    path: '/write',
    component: () => import('../views/WriteArticle.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/settings',
    component: () => import('../views/Settings.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  
  // 检查是否需要登录
  const userStore = useUserStore()
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    // 保存重定向地址
    localStorage.setItem('redirect', to.fullPath)
    next('/login')
  } else {
    next()
  }
})

export default router 